package com.iyue.servlet;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 《图片处理》实现类
 * 
 * @author 孙晓晔
 * @version $Id: ImgServlet.java,v 1.1 2010/10/14 17:07:14 fresh Exp $
 */
public class ImgServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 2470909453605066617L;

	public ImgServlet() {
	}

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String url = url(request.getRequestURI());
		response.sendRedirect(url);
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doGet(request, response);
	}

	/**
	 * 支持旧地URI地址
	 * 
	 * @param s
	 *            /castshowimage/300A225/jV1ViGyBfHe63tEt4BfrEtEWeBfvEt+r4hem4BDmEA==.jpg
	 * @return String
	 */
	public String url(String s) {
		// String s =
		// "/castshowimage/300A225/jV1ViGyBfHe63tEt4BfrEtEWeBfvEt+r4hem4BDmEA==.jpg";
		// s =
		// "/castshowimage/400A400Afalse/jV1ViGyBfHe63tEUEB2rEtfSE-+V4B+rI-9lEBMtiA==.jpg";
		String regex = "([\\w|\\W]+)(/)([\\d]+A[\\d|Afalse]+)(/)([\\w|\\W]+)";

		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(s);
		if (!m.matches()) {
			return null;
		}

		String[] ww = m.group(3).split("A");
		if (ww.length < 2) {
			return null;
		}

		String hh;
		if (ww.length > 2) {
			hh = ww[0] + "_" + ww[1];
		} else {
			hh = ww[0] + "x" + ww[1];
		}

		StringBuffer sb = new StringBuffer();
		sb.append("/img/");
		sb.append(hh);

		String filename = s.substring(s.lastIndexOf("/") + 1);
		String aa;
		for (int i = 0, len = filename.length() - 4; i < len; i += 4) {
			aa = filename.substring(i, i + 1).toLowerCase();
			if (aa.matches("([\\d|a-z]+)")) {
				sb.append("/");
				sb.append(aa);
			}
		}
		sb.append("/");
		sb.append(filename);

		return sb.toString();
	}
}
